package org.jeecg.modules.pay.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.jeecg.boot.starter.rabbitmq.client.RabbitMqClient;
import org.jeecg.common.base.BaseMap;
import org.jeecg.modules.pay.entity.UserAccount;
import org.jeecg.modules.pay.mapper.UserAccountMapper;
import org.jeecg.modules.pay.service.IUserAccountService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @Description: 用户余额表
 * @Author: jeecg-boot
 * @Date:   2022-06-14
 * @Version: V1.0
 */
@Service
public class UserAccountServiceImpl extends ServiceImpl<UserAccountMapper, UserAccount> implements IUserAccountService {

    @Autowired
    private ISysUserService sysUserService;

    @Autowired
    private RabbitMqClient rabbitMqClient;

    @Autowired
    private IUserAccountService userAccountService;

    @Override
    public IPage<UserAccount> getPage(Integer pageNo, Integer pageSize, QueryWrapper<UserAccount> queryWrapper) {
        Page<UserAccount> page = new Page<UserAccount>(pageNo, pageSize);
        return page(page, queryWrapper);
    }

    @Override
    public void add(UserAccount userAccount) {
        save(userAccount);
    }

    @Override
    public List<UserAccount> getByName(String name) {
        return sysUserService.list(new QueryWrapper<SysUser>().eq("realname", name))
                .stream()
                .map(SysUser::getId)
                .map(this::getById)
                .collect(Collectors.toList());
    }

    @Override
    public void addMoney(String id, BigDecimal bigDecimal) {
        BigDecimal balance = userAccountService.getById(id).getBalance();
        BigDecimal add = balance.add(bigDecimal);
        userAccountService.updateById(new UserAccount().setId(id).setBalance(add));

        // 发送消息队列进行充值消费记录
        BaseMap map = new BaseMap();
        map.put("changeNum", bigDecimal);
        map.put("beforeChange", balance);
        map.put("AfterChange", add);
        map.put("id", id);
        rabbitMqClient.sendMessage("accountChange", map);
    }
}
